package ee.ut.re;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class PriceIndex {

	
	Map<String, Integer> monthIndex = new HashMap<String, Integer>();
	
	public PriceIndex() {
		
		try {
			InputStream is = ClassLoader.getSystemResourceAsStream("tallinn_index.xml");
			
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(is);
	
	        NodeList nodes = doc.getElementsByTagName("point");
	      
	        for (int i = 0; i < nodes.getLength(); i++) {
	        	Node node = nodes.item(i);
	        	String key = node.getAttributes().getNamedItem("dvalue").getNodeValue().substring(3);
	        	int value = Integer.valueOf(node.getAttributes().getNamedItem("value").getNodeValue());
	        	monthIndex.put(key, value);
	        }
		} catch (Exception x) {
			throw new RuntimeException(x);
		}
	}
	
	public double getAdjustedPrice(double srcPrice, String srcDate, String destDate) {
		double srcIdx = monthIndex.get(srcDate);
		double destIdx = monthIndex.get(destDate);
		
		double conversionFactor = destIdx / srcIdx;
		return srcPrice * conversionFactor;
				
	}
	
	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
		PriceIndex idx = new PriceIndex();
		
		System.out.println(idx.getAdjustedPrice(1000, "05.2008", "11.2011"));
		Date date = new Date();
		date.setMonth(10);
		Date date2 = new Date();
		date2.setMonth(10);
		System.out.println(idx.getAdjustedPrice(1000.0, date, date2));
	}

	
	
	public double getAdjustedPrice(Double srcPrice, Date saleDate,
			Date adjustDate) {
		DateFormat df = new SimpleDateFormat("MM.yyyy");
		
		return getAdjustedPrice(srcPrice, df.format(saleDate), df.format(adjustDate));
	}
 	
}
